/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { message } from 'antd';
import React, { useState } from 'react';
import styles from './index.less';
import UploadWithCrypto from '@base/components/upload-width-crypto';

const UploadImage: React.FC<any> = (props) => {
  const { defaultText, onChange, value } = props;
  const [loading, setLoading] = useState(false);

  const handleChange = (file: any) => {
    if (file.file.status === 'uploading') {
      setLoading(true);
      return;
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>
        <a>{defaultText}</a>
      </div>
    </div>
  );

  const checkFileSize = (file: any) => {
    const { size, type } = file;
    const isLt5M = size / 1024 / 1024 < 5;
    const fileType = type.split('/')[1];
    const hasAccept = ['jpeg', 'png', 'jpg'].includes(fileType);
    if (!isLt5M) {
      message.error('图片尺寸大于5M');
      return false;
    } else if (!hasAccept) {
      message.error('仅支持png、jpg格式');
      return false;
    } else {
      return true;
    }
  };

  const onSuccess = (result: any) => {
    const { code, data, msg } = result;
    if (code == 0) {
      onChange(data);
    } else {
      message.error(msg);
    }
    setLoading(false);
  };

  return (
    <UploadWithCrypto
      action={'/LargeAmountApply/uploadPic'}
      listType='picture-card'
      accept='.jpg,.png'
      multiple={false}
      showUploadList={false}
      onChange={handleChange}
      beforeUpload={checkFileSize}
      className={styles.uploadImage}
      onSuccess={onSuccess}
    >
      {value ? <img src={value} alt='avatar' width={148} height={100} /> : uploadButton}
    </UploadWithCrypto>
  );
};

export default UploadImage;
